import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { Input, Select, Pop, Upload } from 'zent';
import SelectedImage from '@/components/plugins/selectImage/index';
import find from 'lodash/find';
import fullfillImage from 'zan-utils/fullfillImage';
import { Select as SelectAnt, Popconfirm } from 'antd';
import { connect } from 'dva';
import './css/select.less'
const Option = SelectAnt.Option;
class SKUContainer extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      skuOptions: [],
      newLeafText: '',
      leafValue: [],
      selectLeaf: [],
      selectLeafId: 0,
      id: 0,
      currleafId: 0,
    };
  }

  componentWillMount() {
    let { sku } = this.props;
    let { optionValue } = this.context;
    sku[optionValue] && this.fetchLeafById(sku[optionValue]);
  }

  componentWillReceiveProps(nextProps) {
    let { optionValue } = this.context;
    if (this.state.id === nextProps.sku[optionValue]) return;
    this.fetchLeafById(nextProps.sku[optionValue]);
  }
  imgModal = ref => {
    this.imgmodal = ref;
  };
  showModal = () => {
    this.imgmodal.handleShowModal();
  };
  onImageChange(res) {
    const { sku } = this.props;
    let { optionValue } = this.context;
    let id = this.state.selectLeafId;
    sku.leaf.forEach(item => {
      if (item[optionValue] === id) {
        item.img_url = fullfillImage(res.imageUrl, '');
      }
    });
    this.props.onSKULeafChange(sku.leaf);
    this.imgmodal.handleModalVisible();
  };

  createSkuProp = () => {
    let { sku, dispatch } = this.props;
    let { leafValue, skuOptions, selectLeaf } = this.state;
    if (!this.state.newLeafText)
      return;
    let valueName = this.state.newLeafText;
    dispatch({
      type: 'goods/CreateProductSkuValue',
      params: {
        SkuId: sku.id,
        Name: valueName,
        p: Math.random()
      },
      callBack: (data) => {
        let arr = [];
        if (data.Code != 0)
          return;
        if (!data.Data)
          return;
        if (leafValue.indexOf(parseInt(data.Data.id)) < 0) {

          //临时规格值数组
          if (this.state.selectLeaf.filter(i => i.id == parseInt(data.Data.id)).length < 1) {
            let model = { id: parseInt(data.Data.id), text: valueName, value: parseInt(data.Data.id) }
            selectLeaf.push(model)
            skuOptions.push(model);
          }
          leafValue.push(parseInt(data.Data.id));
          this.setState({ skuOptions, leafValue, selectLeaf }, () => {
            this.forceUpdate()
          })
        }


      }
    });
  }

  createSkuPropBySelcet = (value, callBack) => {
    let { sku, dispatch } = this.props;
    let { leafValue, skuOptions, selectLeaf } = this.state;
    if (!value)
      return;
    let valueName = value;
    dispatch({
      type: 'goods/CreateProductSkuValue',
      params: {
        SkuId: sku.id,
        Name: valueName,
        p: Math.random()
      },
      callBack: (data) => {
        let arr = [];
        if (data.Code != 0)
          return;
        if (!data.Data)
          return;
        if (skuOptions.filter(i => i.id == 0).length > 0) {
          let index = skuOptions.findIndex(item => item.id == 0);
          skuOptions.splice(index, 1);
        }
        if (leafValue.indexOf(parseInt(data.Data.id)) < 0) {
          //临时规格值数组
          if (this.state.selectLeaf.filter(i => i.id == parseInt(data.Data.id)).length < 1) {
            let model = { id: parseInt(data.Data.id), text: valueName, value: parseInt(data.Data.id) }
            selectLeaf.push(model)
            skuOptions.push(model);
          }
          leafValue.push(parseInt(data.Data.id));
          this.setState({ skuOptions, leafValue, selectLeaf, currleafId: parseInt(data.Data.id) }, () => {
            this.forceUpdate()
            if (callBack) {
              callBack();
            }
          })
        }

      }
    });
  }

  handleSearch = (value) => {
    let { skuOptions } = this.state;
    let newLeaf = { id: 0, text: value, value: 0 }
    if (skuOptions.filter(i => i.id == 0).length > 0) {
      let index = skuOptions.findIndex(item => item.id == 0);
      skuOptions.splice(index, 1);
    }
    skuOptions.push(newLeaf);
    this.setState({
      newLeafText: value,
      skuOptions
    });


  }
  fetchLeafById(id) {
    if (!id) return;
    const { dispatch } = this.props;
    dispatch({
      type: 'goods/GetProductSkuValueListByZent',
      payload: {
        id: id,
        p: Math.random()
      },
      callBack: (data) => {
        let arr = [];
        if (data.Code == 0) {
          if (!data.Data) {
            this.setState({
              id: id,
              skuOptions: [],
            })
          } else {
            data.Data.map((item) => {
              arr.push({
                id: item.Id,
                text: item.Name
              });
            })
            this.setState({
              id: id,
              skuOptions: arr,
            })
          }
        }

      }
    });
    // this.context.onFetchSKU(id).then(skuOptions => {
    //   this.setState({
    //     id,
    //     skuOptions,
    //   }, () => {
    //     console.log(skuOptions)
    //   });
    // });
  }

  resetLeaf = () => {
    this.setState({ leafValue: [] });
  };
  OpenImageModal = (id) => {
    this.setState({ selectLeafId: id })

    this.imgmodal.handleShowModal();
  };
  selectSKU = () => {
    let { sku, hasSKUImage } = this.props;
    let { leafValue } = this.state;
    let { optionValue } = this.context;

    const skuLeaf = this.skuLeaf.state.selectedItems.map((item, key) => {
      item[optionValue] = item.value || leafValue[key];
      item.is_show = hasSKUImage;
      delete item.cid;
      return item;
    });

    let skuLeafIds = sku.leaf.map(item => item[optionValue]);
    skuLeaf.forEach(item => {
      if (skuLeafIds.indexOf(item[optionValue]) < 0) {
        sku.leaf.push(item);
      }
    });
    this.resetLeaf();
    this.props.onSKULeafChange(sku.leaf);
  };
  selectSKUAnt = () => {
    let { sku, hasSKUImage } = this.props;
    let { leafValue } = this.state;
    let { optionValue } = this.context;
    const skuLeaf = []

    let leafModel;
    let leafId;
    this.state.selectLeaf.map((item, key) => {
      let leaf = { id: item.id, is_show: hasSKUImage, text: item.text, value: item.id }
      skuLeaf.push(leaf);
    });

    //新增的规格值
    if (this.state.newLeafText) {
      let propsName = this.state.newLeafText;
      if (propsName.length > 20) {
        propsName = propsName.substring(0, 20)
      }
      this.createSkuPropBySelcet(propsName, () => {
        console.log(this.state.currleafId);
        if (this.state.currleafId > 0) {
          let leaf = { id: parseInt(this.state.currleafId), is_show: hasSKUImage, text: propsName, value: parseInt(this.state.currleafId) }
          skuLeaf.push(leaf);
        }
        this.setState({ newLeafText: '', currleafId: 0 });
        let skuLeafIds = sku.leaf.map(item => item[optionValue]);
        skuLeaf.forEach(item => {
          if (skuLeafIds.indexOf(item[optionValue]) < 0) {
            sku.leaf.push(item);
          }
        });
        this.setState({ selectLeaf: [] });
        this.resetLeaf();
        this.props.onSKULeafChange(sku.leaf);
      });
    } else {
      //正常选择
      let skuLeafIds = sku.leaf.map(item => item[optionValue]);
      skuLeaf.forEach(item => {
        if (skuLeafIds.indexOf(item[optionValue]) < 0) {
          sku.leaf.push(item);
        }
      });
      this.setState({ selectLeaf: [] });
      this.resetLeaf();
      this.props.onSKULeafChange(sku.leaf);
    }



  };
  removeSKULeaf(idx, evt) {
    evt && evt.stopPropagation && evt.stopPropagation();

    let { sku } = this.props;
    sku.leaf.splice(idx, 1);
    this.props.onSKULeafChange(sku.leaf);
  }

  createSKULeaf = (evt, leaf) => {

    let { sku } = this.props;
    let { leafValue, skuOptions } = this.state;
    let { onCreateSKU, optionValue, optionText } = this.context;
    if (leaf[optionValue] || typeof leaf[optionText] !== 'string') {
      if (leafValue.indexOf(leaf[optionValue]) < 0) {
        leafValue.push(leaf[optionValue]);
      }
      return false;
    }
    if (!leaf[optionText]) {
      return;
    }
    onCreateSKU({
      text: leaf[optionText],
      id: sku[optionValue],
    }).then(data => {
      let newSKULeaf = {};
      leafValue.push(data);
      newSKULeaf[optionText] = leaf[optionText];
      newSKULeaf[optionValue] = data;
      skuOptions.push(newSKULeaf);
      this.setState({
        newLeafText: '',
        leafValue: [].concat(leafValue),
        skuOptions: [].concat(skuOptions),
      });
    });
  };

  createSKULeafAnt = (evt, leaf) => {
    let { sku } = this.props;
    let { leafValue, skuOptions } = this.state;
    let { onCreateSKU, optionValue, optionText } = this.context;
    let svalue = []

    leaf.map(item => {
      if (item.key) {
        if (item.key == 0) {
          let porpsName = item.props.children
          if (porpsName.length > 20) {
            porpsName = porpsName.substring(0, 20);
          }
          return this.createSkuPropBySelcet(porpsName);
        }
        if (leafValue.indexOf(parseInt(item.key)) < 0) {
          leafValue.push(parseInt(item.key))
          this.setState({ leafValue }, () => {
            this.forceUpdate()
          })
        }
        //临时规格值数组
        if (this.state.selectLeaf.filter(i => i.id == parseInt(item.key)).length < 1) {
          let model = { id: parseInt(item.key), text: item.props.children, value: parseInt(item.key) }
          this.state.selectLeaf.push(model)
        }
      }
    })
    //选中之后 清空  这样 失去焦点事件中 不会添加新的规格值
    this.handleReset(this)
  };

  updateLeafValue = sku => {
    let { optionValue } = this.context;
    let { leafValue } = this.state;
    leafValue = leafValue.filter(item => item !== sku[optionValue]);
    this.setState({ leafValue: [].concat(leafValue) });
  };
  updateLeafValueAnt = e => {
    let { optionValue } = this.context;
    let { leafValue, selectLeaf } = this.state;
    let index = selectLeaf.findIndex(item => {
      return item.id == parseInt(e)
    });
    if (index > -1) {
      selectLeaf.splice(index, 1);
    }
    leafValue = leafValue.filter(item => item !== parseInt(e));
    this.setState({ leafValue: [].concat(leafValue), selectLeaf });
  };
  asyncFilterSKULeaf = keyword => {
    let { optionText, maxLeafTextLength } = this.context;
    let { skuOptions } = this.state;
    if (maxLeafTextLength && maxLeafTextLength > 0) {
      keyword = keyword.substring(0, maxLeafTextLength);
    }
    if (skuOptions.some(item => item[optionText] === keyword)) return;
    this.setState({
      newLeafText: keyword,
    });
  };

  filterSKU = (item, keyword) => {
    let { maxLeafTextLength } = this.context;
    if (maxLeafTextLength && maxLeafTextLength > 0) {
      keyword = keyword.substring(0, maxLeafTextLength);
    }
    return item.text.indexOf(keyword) > -1;
  };

  handleReset = (open) => {
    if (open) {
      this.setState({
        newLeafText: '',
      });
    }
  };

  handleRenameSKULeaf(index) {
    let { sku, onSKULeafChange } = this.props;
    let { optionValue, optionText, onCreateSKU } = this.context;
    let { skuOptions } = this.state;
    let findKey = {};
    findKey[optionText] = this.renameText;
    let skuItem = find(skuOptions, findKey);
    if (skuItem) {
      sku.leaf[index] = skuItem;
      onSKULeafChange(sku.leaf);
      return;
    }
    onCreateSKU({
      text: this.renameText,
      id: sku[optionValue],
    }).then(data => {
      let newSKULeaf = {};
      newSKULeaf[optionText] = this.renameText;
      newSKULeaf[optionValue] = data;
      skuOptions.push(newSKULeaf);
      this.setState({
        skuOptions: [].concat(skuOptions),
      });
      sku.leaf[index] = newSKULeaf;
      onSKULeafChange(sku.leaf);
    });
  }

  renderSKUPopContent() {
    let { optionValue, optionText } = this.context;
    let { leafValue, skuOptions, newLeafText } = this.state;

    // if (newLeafText) {
    //   skuOptions = [].concat(skuOptions);
    //   if (skuOptions.length > 0 && skuOptions[0][optionValue] === 0) {
    //     skuOptions[0][optionText] = newLeafText;
    //   } else {
    //     let newLeaf = {};
    //     newLeaf[optionValue] = 0;
    //     newLeaf[optionText] = newLeafText;
    //     skuOptions.unshift(newLeaf);
    //   }
    // }

    return (
      <div>
        {/* <Select
          ref={skuLeaf => (this.skuLeaf = skuLeaf)}
          data={skuOptions}
          optionValue={optionValue}
         
          tags
          open
          filter={this.filterSKU}
          value={leafValue}
          onAsyncFilter={this.asyncFilterSKULeaf}
          onChange={this.createSKULeaf}
          onDelete={this.updateLeafValue}
          onOpen={this.handleReset}
        /> */}

        <SelectAnt
          ref={skuLeaf => (this.skuLeaf = skuLeaf)}
          mode="multiple"
          //autoClearSearchValue={false}
          // onBlur={this.createSkuProp}
          onSearch={this.handleSearch}
          onDeselect={this.updateLeafValueAnt}
          onChange={this.createSKULeafAnt}
          style={{ width: 200 }}
          autoClearSearchValue={true}
          showSearch
          value={leafValue}
          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          onDropdownVisibleChange={this.handleReset}
        >
          {skuOptions.map(item => <Option key={item.id} value={item.id}>{item.text}</Option >)}
        </SelectAnt>
      </div>
    );
  }

  removeImg(id) {
    const { sku } = this.props;
    let { optionValue } = this.context;
    sku.leaf.forEach(item => {
      if (item[optionValue] === id) {
        item.img_url = '';
      }
    });
    this.props.onSKULeafChange(sku.leaf);
  }

  uploadSuccess(id, imageUrl) {
    const { sku } = this.props;
    let { optionValue } = this.context;
    sku.leaf.forEach(item => {
      if (item[optionValue] === id) {
        item.img_url = fullfillImage(imageUrl[0].src, '!100x100.jpg');
      }
    });
    this.props.onSKULeafChange(sku.leaf);
  }

  render() {
    let { optionValue, optionText, prefix } = this.context;

    let { sku, hasSKUImage, i18n } = this.props;

    return (
      <div className="group-container">
        <div className="sku-list">
          {sku[optionValue] > 0 ?
            (<span style={{ fontSize: 12 }}>规格值：</span>) :
            ('')}
          {sku.leaf.map((item, index) => {

            return (
              <div
                key={index}
                className={cx(`${prefix}-item`, {
                  active: hasSKUImage,
                })}
                style={{ height: '30px', lineHeight: '30px', padding: 0 }}>
                {/* <Pop
                  //trigger="click"
                  position="bottom-center"
                  content={
                    <Input
                      defaultValue={item[optionText]}
                      onChange={evt => (this.renameText = evt.target.value)}
                    />
                  }
                  onConfirm={this.handleRenameSKULeaf.bind(this, index)}
                > */}
                <div>
                  <span className={cx(`${prefix}-item__text`)}>
                    {item[optionText]}
                  </span>
                  <Popconfirm title="确认删除？" onConfirm={this.removeSKULeaf.bind(this, index)} okText="是" cancelText="否">
                    <span
                      className="item-remove"
                    >
                      ×
                    </span>
                  </Popconfirm>
                </div>
                {/* </Pop> */}
                {hasSKUImage && (
                  <div
                    className={cx(
                      'upload-img-wrap',
                      `${prefix}-item__pop-ignore-click`
                    )}
                    style={{ width: 84, height: 84 }}
                  >
                    <div className="arrow" />
                    {item.img_url ? (
                      <div className="upload-img" style={{ width: 78, height: 78 }}>
                        <Popconfirm title="确认删除？" onConfirm={this.removeImg.bind(this, item[optionValue])} okText="是" cancelText="否">
                          <span
                            className="item-remove"
                            title={i18n.container.del}
                          >
                            ×
                        </span>
                        </Popconfirm>
                        <img
                          src={item.img_url}
                          role="presentation"
                          alt=""
                          data-src={item.img_url}
                        />
                        {
                          !item.img_url ?
                            <a onClick={() => this.OpenImageModal(item[optionValue])} style={{ height: '80px', lineHeight: '80px', display: 'block', overflow: 'hidden', fontSize: 30, color: '#e5e5e5' }}> + </a>
                            : null
                        }
                        {/* <Upload
                          triggerClassName={cx(
                            'img-edit',
                            `${prefix}-item__pop-ignore-click`
                          )}
                          materials
                          maxAmount={1}
                          onUpload={this.uploadSuccess.bind(
                            this,
                            item[optionValue]
                          )}
                        >
                          <span className={cx(`${prefix}-item__text`)}>
                            {i18n.container.replace}
                          </span>
                        </Upload> */}
                      </div>
                    ) : (
                        <div>
                          <a onClick={() => this.OpenImageModal(item[optionValue])} style={{ height: '80px', lineHeight: '80px', display: 'block', overflow: 'hidden', fontSize: 30, color: '#e5e5e5' }}> + </a>
                          {/* <Upload
                            materials
                            maxAmount={1}
                            onUpload={this.uploadSuccess.bind(
                              this,
                              item[optionValue]
                            )}
                          >
                            <span>+</span>
                          </Upload> */}
                        </div>
                      )}

                  </div>
                )}
              </div>
            );
          })}
          {sku[optionValue] > 0 ? (


            <Pop
              trigger="click"
              position="bottom-center"
              className={`${prefix}-pop`}
              closeOnClickOutside={false}
              wrapperClassName={`${prefix}-pop`}
              content={this.renderSKUPopContent()}
              onConfirm={this.selectSKUAnt}
              onClose={this.resetLeaf}
            >

              <span className="sku-add" style={{ margin: 0, padding: 0 }}>{i18n.container.add}</span>
            </Pop>

          ) : (
              ''
            )}
        </div>
        <SelectedImage onRef={this.imgModal} selectImage={this.onImageChange.bind(this)} />
      </div >
    );
  }
}

SKUContainer.contextTypes = {
  prefix: PropTypes.string,
  maxLeafTextLength: PropTypes.number,
  optionValue: PropTypes.string,
  optionText: PropTypes.string,
  onFetchSKU: PropTypes.func,
  onCreateSKU: PropTypes.func,
};

export default connect(({ goods, global, loading }) => ({
  goods,
}))(SKUContainer);